import LRContainer from '@/components/CardLayout/LRContainer';
import { addUser, deleteUserById, pageUser, updateUserById } from '@/pages/system/user/api';
import AddRoleMoadl from '@/pages/system/user/components/AddRoleMoadl';
import RoleAssignmentModal from '@/pages/system/user/components/RoleAssignmentModal';
import UserEditModel from '@/pages/system/user/components/UserEditModel';
import { API } from '@/services/typings';
import { useModel } from '@@/exports';
import {
  DeleteOutlined,
  EditOutlined,
  LockOutlined,
  UnlockOutlined,
  UserAddOutlined,
} from '@ant-design/icons';
import { ActionType, ProColumns, ProDescriptions, ProTable } from '@ant-design/pro-components';
import { useRequest } from 'ahooks';
import { Alert, Button, message, Popconfirm, Tag, Tooltip } from 'antd';
import React, { useState } from 'react';

const UserManager: React.FC = () => {
  const actionRef = React.useRef<ActionType>();
  const { loadDictData, loading } = useModel('dict');
  const [selectedUser, setSelectedUser] = useState<API.CurrentUser | null>(null);
  const { data: userTypeDictData } = useRequest(() => loadDictData('user-type'));

  const columns: ProColumns<API.CurrentUser>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      ellipsis: true,
      tooltip: '姓名',
      key: 'name',
      width: 100,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      ellipsis: true,
      tooltip: '用户名',
      key: 'username',
      copyable: true,
      width: 100,
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      ellipsis: true,
      tooltip: '昵称',
      key: 'nickname',
      width: 100,
    },
    {
      title: '用户类型',
      dataIndex: 'type',
      ellipsis: true,
      key: 'type',
      hideInSearch: false,
      width: 80,
      valueType: 'select',
      align: 'center',
      request: async () => await loadDictData('user-type'),
      render: (text, record) => {
        const item = userTypeDictData.find((d: any) => d.value === record.type);
        return item ? <Tag color={item.color}>{item.label}</Tag> : '-';
      },
    },
    {
      title: '联系方式',
      dataIndex: 'phone',
      ellipsis: true,
      key: 'phone',
      align: 'center',
      width: 100,
    },
    {
      title: '状态',
      dataIndex: 'status',
      ellipsis: true,
      key: 'status',
      valueType: 'select',
      align: 'center',
      width: 80,
      valueEnum: {
        '0': {
          text: '正常',
          status: 'Success',
        },
        '1': {
          text: '停用',
          status: 'Error',
        },
      },
    },
  ];

  return (
    <LRContainer
      leftTitle="用户列表"
      rightTitle="用户详情"
      leftSpan={65}
      rightSpan={35}
      leftExtra={[
        <UserEditModel
          isAdd={true}
          key="add"
          onSubmit={async (values) => {
            const { data } = await addUser(values);
            if (data) {
              actionRef.current?.reload();
              message.success('添加成功');
            }
            return data;
          }}
          triggerButton={
            <Tooltip title="添加用户">
              <Button type="primary" shape="circle" size="small" icon={<UserAddOutlined />} />
            </Tooltip>
          }
        />,
      ]}
      rightExtra={
        selectedUser && (
          <div style={{ display: 'flex', gap: '8px' }}>
            <UserEditModel
              isAdd={false}
              user={selectedUser}
              key="update"
              onSubmit={async (values) => {
                values.id = selectedUser.id;
                const { data } = await updateUserById(values);
                if (data) {
                  actionRef.current?.reload();
                  message.success('修改成功');
                }
                return data;
              }}
              triggerButton={
                <Tooltip title="修改用户">
                  <Button type="primary" shape="circle" size="small" icon={<EditOutlined />} />
                </Tooltip>
              }
            />
            <Popconfirm
              key="delete"
              title="确认删除"
              description={`确认删除【${selectedUser.name}】用户吗？`}
              okText="确认"
              cancelText="取消"
              onConfirm={async () => {
                const { data } = await deleteUserById(selectedUser.id);
                if (data) {
                  actionRef.current?.reload();
                  message.success('删除成功');
                  setSelectedUser(null);
                }
              }}
            >
              <Tooltip title="删除用户">
                <Button danger shape="circle" size="small" icon={<DeleteOutlined />} />
              </Tooltip>
            </Popconfirm>
            <Tooltip title={selectedUser.status === '0' ? '封禁用户' : '启用用户'}>
              <Button
                type={selectedUser.status === '0' ? 'default' : 'primary'}
                shape="circle"
                size="small"
                icon={selectedUser.status === '0' ? <LockOutlined /> : <UnlockOutlined />}
                onClick={async () => {
                  const { data } = await updateUserById({
                    id: selectedUser.id,
                    status: selectedUser.status === '0' ? '1' : '0',
                  } as API.CurrentUser);
                  if (data) {
                    actionRef.current?.reload();
                    message.success('修改成功');
                  }
                }}
              />
            </Tooltip>
            <RoleAssignmentModal key="role" userId={selectedUser.id as any} />
            <AddRoleMoadl key="addrole" userId={selectedUser.id as any} />
          </div>
        )
      }
      leftContent={
        <ProTable<API.CurrentUser>
          actionRef={actionRef}
          rowKey="id"
          search={{
            labelWidth: 'auto',
            span: 6,
            filterType: 'light',
          }}
          ghost={true}
          toolbar={{
            style: { padding: '0px 0' },
          }}
          pagination={{
            pageSize: 15,
          }}
          request={async (params, sort, filter) => {
            const { data } = await pageUser({
              ...params,
              current: params.current,
              pageSize: params.pageSize,
            });
            return data;
          }}
          tableAlertRender={false}
          columns={columns}
          rowSelection={{
            type: 'radio',
            selectedRowKeys: selectedUser ? [selectedUser.id] : [],
            onChange: (_, rows) => setSelectedUser(rows[0]),
          }}
          onRow={(record) => ({
            onClick: () => setSelectedUser(record),
            style: { cursor: 'pointer' },
          })}
        />
      }
      rightContent={
        selectedUser ? (
          <ProDescriptions
            column={1}
            dataSource={selectedUser}
            bordered
            size="small"
            labelStyle={{
              width: '100px',
              color: '#666',
              fontWeight: 500,
            }}
            contentStyle={{
              color: '#1f1f1f',
            }}
            columns={[
              {
                title: '姓名',
                dataIndex: 'name',
                copyable: true,
                ellipsis: true,
              },
              {
                title: '用户名',
                dataIndex: 'username',
                copyable: true,
                ellipsis: true,
              },
              {
                title: '联系方式',
                dataIndex: 'phone',
                copyable: true,
                ellipsis: true,
              },
              {
                title: '状态',
                dataIndex: 'status',
                valueEnum: {
                  '0': { text: '正常', status: 'Success' },
                  '1': { text: '停用', status: 'Error' },
                },
              },
              {
                title: '用户类型',
                dataIndex: 'type',
                render: (_, record) => {
                  const item = userTypeDictData?.find((d: any) => d.value === record.type);
                  return item ? <Tag color={item.color}>{item.label}</Tag> : '-';
                },
              },
            ]}
          />
        ) : (
          <div
            style={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              height: '100%',
              padding: '24px',
            }}
          >
            <Alert
              message="请选择一个用户"
              type="info"
              showIcon
              style={{
                width: '100%',
                maxWidth: '400px',
              }}
            />
          </div>
        )
      }
    />
  );
};

export default UserManager;
